extends Node
class_name WizardState
## 用来控制敌人状态和移动
@export var wizard: Wizard
@onready var sprite: AnimatedSprite2D = %sprite
@onready var state_chart: StateChart = %StateChart
@onready var walk: AtomicState = %walk
@onready var die: AtomicState = %die
@onready var attack: AtomicState = %attack
@onready var run_away: AtomicState = %runAway
@onready var hurt: AtomicState = %hurt
@onready var rage: AtomicState = %Rage
@onready var wizard_animations: WizardAnimations = %WizardAnimations
@onready var enemy_hit_box_component: EnemyHitBoxComponent = %EnemyHitBoxComponent
@onready var enemy_health_component: EnemyHealthComponent = %EnemyHealthComponent
@onready var attack_area: Area2D = %AttackArea

## 计算技能时间
var time: float = 0
## 计算逃跑时间
var run_away_time: float = 0
var target_player:Player:
	get:
		return Utils.player
		
func _ready() -> void:
	# 连接所有状态信号
	walk.state_physics_processing.connect(on_walk_physics_processing)
	die.state_entered.connect(on_die_entered)
	attack.state_physics_processing.connect(on_attack_physics_processing)
	run_away.state_physics_processing.connect(on_run_away_physics_processing)
	hurt.state_entered.connect(on_hurt_entered)
	rage.state_entered.connect(on_rage_entered)
	wizard.die.connect(on_die)
	enemy_health_component.hurt.connect(on_hurt)
	
func state_send_event(_name: String):
	state_chart.send_event(_name)
	
#region 状态处理逻辑
## 行走状态物理处理
func on_walk_physics_processing(_delta):
	# 检查玩家是否隐身
	var player_is_stealthed = EnemyManager.is_player_stealthed()
	## 逃跑时和脱离攻击范围都会增加技能蓄力
	if target_player != null and not player_is_stealthed: # 添加hit检查和隐身检查
		wizard_animations.anim_play("walk", wizard.wizard_stats.get_float("anim_speed"))
		var distance = owner.global_position.distance_to(target_player.global_position)
		if distance <= wizard.wizard_stats.get_float("safe_distance"):
			run_away_time += _delta
			owner.velocity = _get_safe_velocity()
			owner.move_and_slide()
		elif distance <= wizard.wizard_stats.get_float("attack_range") and wizard.wizard_stats.get_bool("can_attack"):
			state_send_event("to_attack")
		else:
			run_away_time += _delta
			owner.velocity = _get_safe_velocity()
			owner.move_and_slide()
		if run_away_time >= wizard.wizard_stats.get_float("rage_time") / 2:
			state_send_event("to_rage")
			run_away_time = 0
			return
	else:
		# 玩家隐身时，弓箭手完全停止并播放idle动画
		wizard_animations.anim_play("idle", wizard.wizard_stats.get_float("anim_speed"))
		owner.velocity = Vector2.ZERO
		wizard.velocity = Vector2.ZERO
		return  # 直接返回，不执行move_and_slide()
	
	wizard.move_and_slide()

## 死亡状态进入
func on_die_entered():
	state_send_event("to_die")
	set_physics_process(false)
	sprite.play("die")
	await sprite.animation_finished
	var tween = create_tween()
	tween.tween_property(owner,"modulate",Color(1,1,1,0),2)
	await tween.finished
	wizard.queue_free()
	EventBus.push_event("boss_die")

## 受伤状态进入
func on_hurt_entered():
	wizard_animations.anim_play("hurt")
	await sprite.animation_finished
	state_send_event("to_walk")

#endregion


#func _on_attack_area_area_entered(_area: Area2D) -> void:
	#enemy.append(_area)
	#state_send_event("to_attack")
#
#func _on_attack_area_area_exited(_area: Area2D) -> void:
	#enemy.erase(_area)
	#state_send_event("to_walk")

func on_attack_physics_processing(_delta: float):
	# 检查玩家是否隐身
	var player_is_stealthed = EnemyManager.is_player_stealthed()
	
	# 如果玩家隐身，停止攻击并返回行走状态
	if player_is_stealthed:
		state_send_event("to_walk")
		return
		
	time += _delta
	if time >= wizard.wizard_stats.get_float("rage_time"):
		state_send_event("to_rage")
		time = 0
		return
	if wizard.wizard_stats.get_bool("can_attack") == false:
		return
	owner.find_player_and_flip_h()
	wizard.wizard_stats.set_bool("can_attack", false) 
	wizard.animation_player.play("attack2", wizard.wizard_stats.get_float("anim_speed"))
	wizard.wizard_stats.set_vector2("target_player_postion", target_player.global_position)
	await get_tree().create_timer(wizard.wizard_stats.get_float("attack_cooldown")).timeout
	wizard.wizard_stats.set_bool("can_attack", true)
	state_send_event("to_walk")
		

func on_die() -> void:
	state_send_event("to_die")

func on_hurt() -> void:
	state_send_event("to_hurt")

func _get_safe_velocity() -> Vector2:
	var desired_velocity := Vector2.ZERO
	if target_player != null:
		# 检查玩家是否隐身
		var player_is_stealthed = EnemyManager.is_player_stealthed()
		
		# 如果玩家隐身，返回零速度
		if player_is_stealthed:
			return Vector2.ZERO
		
		var distance = owner.global_position.distance_to(target_player.global_position)
		var direction = owner.global_position.direction_to(target_player.global_position)
		# 如果距离大于攻击范围，向玩家移动
		if distance > wizard.wizard_stats.get_float("attack_range"):
			desired_velocity = direction * wizard.wizard_stats.get_float("speed")
		# 如果距离小于最小安全距离，远离玩家
		elif distance < wizard.wizard_stats.get_float("safe_distance"): # 使用攻击范围的70%作为最小安全距离
			desired_velocity = -direction * wizard.wizard_stats.get_float("speed") * 5
		# 在理想范围内，尝试保持位置或进行小幅度移动
		else:
			# 可以添加小幅度的横向移动，使弓箭手的移动更自然
			var perpendicular = Vector2(-direction.y, direction.x)
			desired_velocity = perpendicular * wizard.wizard_stats.get_float("speed") * 0.5 * sin(Time.get_ticks_msec() / 1000.0)
		if direction.x < 0:
			owner.flip_h(true)
		elif direction.x > 0:
			owner.flip_h(false)
	return desired_velocity.limit_length(wizard.wizard_stats.get_float("speed"))

## 逃跑状态物理处理 
func on_run_away_physics_processing(_delta):
	wizard.velocity = -wizard.direction * (wizard.SPEED * 1.5)
	wizard.move_and_slide()

## 状态：隐身技能（狂暴）
func on_rage_entered():
	wizard.wizard_skill.rage()
	Utils.show_string_label_c("冰霜", wizard)
